#include <func.h>
#include "head.h"

int isLegalUser(MYSQL *db, char *userName, int netFd){
    //发送password
    int dataLength;
    recv(netFd, &dataLength, sizeof(dataLength), MSG_WAITALL);
    char password[100] = {0};
    recv(netFd, password, dataLength, MSG_WAITALL);

    //从数据库拿到盐值和密文
    char sqlCommand[100] = {0};
    sprintf(sqlCommand, "select salt, crypt from user_login_info where usr_name = '%s';", userName);
    int qret = mysql_query(db, sqlCommand);
    if(qret != 0){
        printf("Error: %s\n", mysql_error(db));
        return -1;
    }
    MYSQL_RES *result = mysql_store_result(db);
    char salt[30] = {0};
    char cryptograph[500] = {0};
    MYSQL_ROW row = mysql_fetch_row(result);
    if(row == NULL){
        return -1;
    }
    strcpy(salt, row[0]);
    strcpy(cryptograph, row[1]);
    
    //向客户端发送盐值
    train_t t;
    strcpy(t.buf, salt);
    t.dataLength = strlen(t.buf);
    send(netFd, &t, sizeof(t.dataLength)+t.dataLength, MSG_NOSIGNAL);

    //接收密文
    int dataLength;
    char inputCryptograph[500] = {0};
    recv(netFd, &dataLength, sizeof(dataLength), MSG_WAITALL);
    recv(netFd, inputCryptograph, dataLength, MSG_WAITALL);

    //比较密文，是否为合法用户
    if(strcmp(inputCryptograph, cryptograph) == 0){
        puts("legal user");
        send(netFd, "1", 1, MSG_NOSIGNAL);
        return 0;
    }else{
        puts("ilegal user");
        send(netFd, "0", 1, MSG_NOSIGNAL);
        return -1;
    }
}